using B.S.XZYData.Api.Wrter.Application.Command.SalesOrder;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using SalesOrderEntity = B.S.XZYData.Domain.XZY.SalesOrder;
using SalesOrderProductEntity = B.S.XZYData.Domain.XZY.SalesOrderProduct;

namespace B.S.XZYData.Api.Wrter.Application.Handler.SalesOrder
{
    /// <summary>
    /// 新增销售订单处理器
    /// </summary>
    public class AddSalesOrderHandler : IRequestHandler<AddSalesOrderCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<SalesOrderEntity> _salesOrderRepo;
        private readonly IBaseRepository<SalesOrderProductEntity> _salesOrderProductRepo;

        public AddSalesOrderHandler(
            IBaseRepository<SalesOrderEntity> salesOrderRepo,
            IBaseRepository<SalesOrderProductEntity> salesOrderProductRepo)
        {
            _salesOrderRepo = salesOrderRepo;
            _salesOrderProductRepo = salesOrderProductRepo;
        }

        public async Task<ApiResult<int>> Handle(AddSalesOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 生成单据编号（如果未提供）
                var orderNo = request.OrderNo;
                if (string.IsNullOrEmpty(orderNo))
                {
                    orderNo = GenerateOrderNo();
                }

                // 检查单据编号是否已存在
                var existingOrders = await _salesOrderRepo.GetAllAsync(x => x.OrderNo == orderNo && !x.IsDeleted);
                if (existingOrders.Any())
                {
                    return ApiResult<int>.Error("单据编号已存在");
                }

                // 创建销售订单
                var salesOrder = new SalesOrderEntity
                {
                    OrderNo = orderNo,
                    Remark = request.Remark,
                    CreateTime = DateTime.Now,
                    CreatorId = 1, // 这里应该从当前用户上下文获取
                    IsDeleted = false
                };

                // 插入主表
                var rows = await _salesOrderRepo.CreateAsync(salesOrder);

                // 通过单号回查以获取数据库生成的主键ID（避免把受影响行数当作主键）
                var insertedOrder = (await _salesOrderRepo.GetAllAsync(x => x.OrderNo == orderNo && !x.IsDeleted))
                    .OrderByDescending(x => x.Id)
                    .FirstOrDefault();
                if (insertedOrder == null)
                {
                    return ApiResult<int>.Error("新增销售订单失败：未获取到主键ID");
                }
                var orderId = insertedOrder.Id;

                // 创建产品明细
                if (request.Products != null && request.Products.Any())
                {
                    var productDetails = request.Products.Select(p => new SalesOrderProductEntity
                    {
                        SalesOrderId = orderId,
                        ProductCode = p.ProductCode,
                        ProductName = p.ProductName,
                        ProductSpec = p.ProductSpec,
                        WorkOrderNo = p.WorkOrderNo,
                        Quantity = p.Quantity,
                        CompletedQuantity = 0,
                        CreateTime = DateTime.Now,
                        CreatorId = 1, // 这里应该从当前用户上下文获取
                        ModifyTime = null, // 新增时修改时间为空
                        ModifierId = null, // 新增时修改人为空
                        IsDeleted = false
                    }).ToList();

                    await _salesOrderProductRepo.CreateBatchAsync(productDetails);
                }

                return ApiResult<int>.Success(orderId);
            }
            catch (Exception ex)
            {
                return ApiResult<int>.Error($"新增销售订单失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 生成单据编号
        /// </summary>
        /// <returns></returns>
        private string GenerateOrderNo()
        {
            return $"XSDD{DateTime.Now:yyyyMMddHHmmss}{new Random().Next(1000, 9999):D4}";
        }
    }
}
